/*
 * @version:
 * @Company:
 * @Description:
 * @FilePath: \src\crud\core\crudMethods.ts
 */
import { useLoading } from '/@/components/Loading';
import { message, Modal } from 'ant-design-vue';
import { merge, isFunction } from 'lodash-es';
import { baseParamsInter, toDelInter, toDetailInter } from '../interFace/crudMethods';
export function crudMethods(crud) {
  const [openFullLoading, closeFullLoading] = useLoading({
    tip: '加载中...',
  });
  const methods = {
    /**
     * @vuese
     * @Description: 打开全局Loading 可默认配置时长
     * @arg {*}
     */
    closeLoading(times: string | number) {
      setTimeout(() => {
        closeFullLoading();
      }, times || crud.times.timeout);
    },
    /**
     * @vuese
     * @Description: 获取唯一ID
     * @arg {*}
     */
    getUuid() {
      var s: Array<any> = [];
      var hexDigits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = '4';
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = '-';
      let uuid = s.join('');
      return uuid;
    },
    dealHook(fn) {
      return fn !== false;
    },
    toQuery() {
      crud.pages.page.currentPage = 1;
      this.toRefresh();
    },
    toRefresh() {
      openFullLoading();
      return new Promise((resolve, reject) => {
        crud.crudMethod.getAPI(this.getQueryParams()).then((res: any) => {
          const { code, rows, result, total } = res.data;
          if (crud.successResCode.includes(code)) {
            crud.grids.grid.data = rows || result.items;
            crud.pages.page.total = total;
            this.closeLoading(500);
          }
          resolve(res);
        });
      }).finally(() => {
        this.closeLoading(5000);
      });
    },
    toAdd() {
      return new Promise((resolve, reject) => {
        crud.formStatus = 1;
        crud.dialog.title = `新增-${crud.title}`;
        crud.forms.form.model = JSON.parse(JSON.stringify(crud.forms.form.defaultForm));
        crud.dialog.visible = true;
        resolve(true);
      });
    },
    /**
     * @vuese
     * @Description: 编辑接口 调用查询详情
     * @arg {*} params 参数
     * @arg {*} api 自定义接口
     * @arg {*} before 处理前
     * @arg {*} after 处理后
     */
    async toEdit({ params = null || {}, api = null, before = null, after = null }: baseParamsInter) {
      crud.dialog.title = `编辑-${crud.title}`;
      crud.formStatus = 2;
      if (!api && !isFunction(crud.crudMethod.detailAPI)) {
        throw new Error(`请传入对应的详情API`);
      }
      if (!(await this.dealHook(before?.({ crud })))) return;
      await this.toDetail({ ...arguments[0] }).then(async (res: any) => {
        if (!(await this.dealHook(after?.({ crud, res })))) return;
      });
    },
    /**
     * @vuese
     * @Description:
     * @arg {object} params 删除参数
     * @arg {object} useConfirm 是否使用模态框
     * @arg {*} api 接口
     * @arg {*} modal
     */
    toDel({ params = null || {}, useConfirm = true, api = null, before = null, after = null, refresh = true }: toDelInter) {
      if (!isFunction(crud.crudMethod.delAPI)) {
        throw new Error(`请传入对应的删除API`);
      }
      const fn = async ({ success, error }: any) => {
        openFullLoading();
        const delAPI = api ?? crud.crudMethod.delAPI;
        delAPI(params)
          .then(async (res) => {
            try {
              const { code } = res?.data;
              if (crud.successResCode.includes(code)) {
                if (!(await this.dealHook(after?.({ crud, res })))) return;
                this.closeLoading(500);
                refresh && this.toRefresh();
                success(res);
              } else {
                error(res);
              }
            } catch {}
          })
          .catch((err) => {
            error(err);
          })
          .finally(() => {
            this.closeLoading(5000);
          });
      };
      return new Promise(async (resolve, reject) => {
        if (!(await this.dealHook(before?.({ crud })))) return;
        if (useConfirm) {
          Modal.confirm({
            title: '确认删除',
            content: '是否删除选中数据',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              fn({ success: (res) => resolve(res), error: (err) => reject(err) });
            },
          });
        } else {
          fn({ success: (res) => resolve(res), error: (err) => reject(err) });
        }
      });
    },
    /**
     * @vuese
     * @Description: 详情方法
     * @arg {*} params
     * @arg {*} api
     */
    async toDetail({ params = null || {}, api = null, before = null, after = null }: toDetailInter) {
      if (!api && !isFunction(crud.crudMethod.detailAPI)) {
        throw new Error(`请传入对应的详情API`);
      }
      if (!(await this.dealHook(before?.({ crud })))) return;
      const detailAPI = api ?? crud.crudMethod.detailAPI;
      return new Promise((resolve, reject) => {
        detailAPI(params)
          .then(async (res) => {
            try {
              const { code } = res?.data;
              if (crud.successResCode.includes(code)) {
                this.closeLoading(500);
                if (!(await this.dealHook(after?.({ crud, res })))) return;
                resolve(res);
              } else {
                reject(res);
              }
            } catch {}
          })
          .catch((err) => {
            reject(err);
          })
          .finally(() => {
            this.closeLoading(5000);
          });
      });
    },
    /**
     * @vuese
     * @Description: 保存
     * @arg {*} params
     * @arg {*} api
     * @arg {*} before
     * @arg {*} after
     */
    async toSave({ params = null || {}, api = null, before = null, after = null }: baseParamsInter) {
      if (!isFunction(crud.crudMethod.saveAPI)) {
        throw new Error(`请传入对应的保存API`);
      }
      if (!(await this.dealHook(before?.({ crud })))) return;
      const saveAPI = api ?? crud.crudMethod.saveAPI;
      return new Promise(async (resolve, reject) => {
        try {
          const value = await crud.useForm.formMethods.validate();
          saveAPI(params)
            .then(async (res) => {
              try {
                const { code } = res?.data;
                if (crud.successResCode.includes(code)) {
                  this.closeLoading(500);
                  if (!(await this.dealHook(after?.({ crud, res })))) return;
                  resolve(res);
                } else {
                  reject(res);
                }
              } catch {}
            })
            .catch((err) => {
              reject(err);
            })
            .finally(() => {
              this.closeLoading(5000);
            });
        } catch {}
      });
      // try {
      //   await crud.crudMethod.saveAPI({ ...crud.useForm.formMethods.getFieldsValue() });
      //   setTimeout(() => {
      //     closeModal();
      //     message.success('操作成功！');
      //   }, 500);
      // } catch {
      //   message.error('操作失败！');
      // }
    },
    changeModal({ modal, visible, params }) {
      modal.openModal(visible, params);
      crud.dialog.visible = visible; // 记录当前模态框状态
    },
    getQueryParams() {
      return {
        ...crud.defaultParams,
        current: crud.pages.page.currentPage,
        size: crud.pages.page.pageSize,
      };
    },
  };
  return { ...methods };
}
